// 法律文档展示页面
const auth = require('../../utils/auth.js');
const app = getApp();

Page({
  data: {
    documentType: '',
    documentTitle: '',
    documentContent: '',
    formattedContent: '',
    needsAgreement: false,
    documentId: null
  },

  onLoad: function(options) {
    const { type, title, content, needsAgreement, documentId } = options;
    
    this.setData({
      documentType: type || '',
      documentTitle: decodeURIComponent(title || ''),
      documentContent: decodeURIComponent(content || ''),
      needsAgreement: needsAgreement === 'true',
      documentId: documentId ? parseInt(documentId) : null
    });
    
    this.formatContent();
  },

  // 格式化文档内容
  formatContent: function() {
    let content = this.data.documentContent;
    
    // 简单的Markdown转HTML
    content = content
      .replace(/# (.*?)\n/g, '<h1>$1</h1>')
      .replace(/## (.*?)\n/g, '<h2>$1</h2>')
      .replace(/### (.*?)\n/g, '<h3>$1</h3>')
      .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
      .replace(/\*(.*?)\*/g, '<em>$1</em>')
      .replace(/\n\n/g, '</p><p>')
      .replace(/\n/g, '<br/>');
    
    // 包装在段落标签中
    content = `<p>${content}</p>`;
    
    this.setData({
      formattedContent: content
    });
  },

  // 同意文档
  agreeDocument: function() {
    if (!this.data.documentId) {
      wx.showToast({
        title: '文档信息错误',
        icon: 'error'
      });
      return;
    }

    const apiBaseUrl = app.globalData.apiBaseUrl;
    
    wx.request({
      url: `${apiBaseUrl}/user/privacy/agreements`,
      method: 'POST',
      header: {
        'Authorization': 'Bearer ' + auth.getToken(),
        'Content-Type': 'application/json'
      },
      data: {
        document_ids: [this.data.documentId]
      },
      success: (res) => {
        if (res.data && res.data.success) {
          wx.showToast({
            title: '确认成功',
            icon: 'success'
          });
          
          // 延迟返回，让用户看到成功提示
          setTimeout(() => {
            wx.navigateBack();
          }, 1500);
        } else {
          wx.showToast({
            title: '确认失败',
            icon: 'error'
          });
        }
      },
      fail: (error) => {
        console.error('确认文档失败:', error);
        wx.showToast({
          title: '确认失败',
          icon: 'error'
        });
      }
    });
  },

  // 返回上一页
  navigateBack: function() {
    wx.navigateBack();
  }
});
